<template>
  <div class="detail">
    <nav-bar class="navBar">
      <span slot="left" class="iconfont icon-huitui leftInfo" @click="$router.back()"></span>
      <div slot="center" class="centerInfo">
        <span v-for="(item,index) in navInfo" :key="item.id" @click="navClick(index)" :class="{'active': navIndex==index}">
          <i class="iconfont icon-31dingwei" v-show="navIndex==index"></i>
          {{item.title}}
        </span>
      </div>
      <span slot="right" class="iconfont icon-gengduo right-icon"></span>
    </nav-bar>
    <scroll class="content" ref="content" @scroll="pageScroll">
      <div class="mTop">
        <slide :img-list="swiperInfo" class="slide"></slide>

        <div class="delateInfo">
          <p class="title">{{delateInfo.name}}</p>
          <p class="desc">{{delateInfo.subtitle}}</p>
          <div class="clearfix">
            <p class="price fl">￥{{delateInfo.price}}</p>
            <p class="fr">库存{{delateInfo.stock}}件</p>
          </div>
        </div>

        <div class="desc" ref="descTop">
          <p></p>
          <ul class="delate-desc">
            <li>概述</li>
            <li>参数</li>
            <li>安装服务</li>
            <li>常见问题</li>
          </ul>
          <div class="desc-info" v-html="delateInfo.detail">
          </div>
        </div>
        <recommend :recommend-list-info="recommendList" class="recommendList" ref="recommendTop"></recommend>

      </div>

    </scroll>

    <div class="footer">
      <div class="item">
        <span class="iconfont icon-kefu"></span>
        <span>客服</span>
      </div>
      <div class="item" @click="$router.push('/cart')">
        <span class="iconfont icon-gouwuche"></span>
        <span>购物车</span>
      </div>
      <div class="item handle">
        <a href="javascript:;" class="addCart" @click="addCart">加入购物车</a>
        <a href="javascript:;" class="buy">立即购买</a>
      </div>
    </div>
    <van-sku v-model="show" :sku="sku" :goods="goods" :goods-id="goodsId" :hide-stock="sku.hide_stock" @add-cart="onAddCartClicked" @stepper-change="onStepperChange" :quota="quota" :show-header-image="showImg" />
  </div>
</template>
<script>
import navBar from 'components/common/navbar/navBar'
import Slide from 'components/common/swiper/Slide'
import Recommend from 'components/content/recommend/Recommend'


import Scroll from 'components/common/scroll/Scroll'

import { Sku, Toast } from 'vant';


export default {
  name: '',
  data() {
    return {
      navIndex: 0,
      id: this.$route.params.id,
      delateInfo: [], //详情页数据
      swiperInfo: [], //轮播图处理后的数据
      recommendList: [],
      show: false,
      position: 0,
      navInfo: [
        {
          id: 1,
          title: '商品',
        },
        {
          id: 2,
          title: '商品详情',
        },
        {
          id: 3,
          title: '商品推荐',
        }


      ],
      // 信息配置
      sku: {
        tree: [
          {
            k: '颜色', // skuKeyName：规格类目名称
            v: [{

            },
            {
              id: '002',
              name: '蓝色',
              imgUrl: '',
              previewImgUrl: '',
            }
            ],
            k_s: 's1' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
          }
        ],
        list: [

        ],
        price: '', // 默认价格（单位元）
        stock_num: 0, // 商品总库存
        collection_id: '', // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
      },
      quota: 3,
      // 商品配置
      goods: {
        // 商品标题
        title: '',
        // 默认商品 sku 缩略图
        picture: ''
      },
      // 商品id
      goodsId: this.$route.params.id,
      // 商品数量
      count: 1,
      price: 0,
      tubDistance: [],//主题距离
      showImg: false
    }

  },
  components: {
    navBar,
    Slide,
    Recommend,
    Scroll,

    [Sku.name]: Sku,
    [Toast.name]: Toast,
  },

  created() {
    this.getDelateInfo()
    this.getRecommendInfo()
  },



  methods: {
    pageScroll(position) {
      this.distance(-position.y)
    },
    distance(position) {
      let leg = this.tubDistance.length
      for (let i = 0; i < leg; i++) {
        let iPos = this.tubDistance[i]
        if (position >= iPos && position < this.tubDistance[i + 1]) {
          // 赋值样式索引
          if (this.navIndex !== i) {
            this.navIndex = i;
          }
          return
        }
      }

    },
    // 监听商品数量的变化
    onStepperChange(val) {
      this.count = val
    },
    // 添加购物车
    async onAddCartClicked() {
      // 发送请求
      if (window.sessionStorage.getItem('token')) {
        const res = await this.$require({
          url: '/cart/add',
          method: 'post',
          data: {
            productId: this.goodsId,
            count: this.count
          }
        })

        if (res.status == 0) {
          Toast('添加成功~')
          this.show = false
          let cartInfo = []
          cartInfo.push({
            id: this.goodsId,
            count: this.count,
            price: this.price,
            isChecked: false
          })
          // 将数据保存在store中

          this.$store.dispatch('saveCartInfo', cartInfo)
        } else {
          Toast('加入失败~')
        }
      } else {
        Toast('请先登录~')

        setTimeout(() => {
          this.$router.push('/login')
        }, 1000)
      }
    },
    //添加购物车处理
    addCart() {
      this.show = true
    },

    // 头部导航栏处理事件
    navClick(index) {
      this.navIndex = index
      this.$refs.content.scrollTo(0, -this.tubDistance[index], 500)
    },
    // 获取详情数据
    async getDelateInfo() {
      const res = await this.$require({
        url: '/product/detail',
        method: 'get',
        params: {
          id: this.id
        }
      })
      if (res.status == 0) {

        this.delateInfo = res.data
        this.goods.title = res.data.name

        // 处理轮播图数据 
        if (res.data.subImages) {
          var subImg = res.data.subImages.split(',')
          var imgHost = res.data.imageHost
          this.showImg = true
          subImg.forEach(item => {
            this.swiperInfo.push({
              imgUrl: imgHost + item
            })
          })
          // sku 商品数据设置
          this.goods.picture = imgHost + subImg[1]

          this.sku.price = res.data.price  //设置价格
          this.sku.stock_num = parseInt(res.data.stock) //设置库存
          this.sku.collection_id = res.data.id
          this.sku.list[0] = {
            id: res.data.id, // skuId，下单时后端需要
            price: res.data.price * 100, // 价格（单位分）
            s1: res.data.id, // 规格类目 k_s 为 s1 的对应规格值 id
            stock_num: parseInt(res.data.stock)// 当前 sku 组合对应的库存
          }
          this.sku.tree[0].v[0] = {
            id: res.data.id, // skuValueId：规格值 id
            name: '红色', // skuValueName：规格值名称
            imgUrl: imgHost + subImg[1], // 规格类目图片，只有第一个规格类目可以定义图片
            previewImgUrl: imgHost + subImg[1], // 用于预览显示的规格类目图片
          }
          this.sku.tree[0].v[1] = {
            id: '002',
            name: '蓝色',
            imgUrl: imgHost + subImg[2], // 规格类目图片，只有第一个规格类目可以定义图片
            previewImgUrl: imgHost + subImg[2], // 用于预览显示的规格类目图片
          }
        } else {
          this.sku.tree[0].v.forEach(item => {
            item.name = ''
            item.imgUrl = ""
            item.previewImgUrl = ''
          })

        }





        // 获取元素高度
        this.$nextTick(() => {
          this.$refs.content.refresh()
          // 获取元素高度
          this.tubDistance.push(0)
          this.tubDistance.push(this.$refs.descTop.offsetTop)
          if (window.sessionStorage.getItem('token')) {
            this.tubDistance.push(this.$refs.recommendTop.$el.offsetTop)
            this.tubDistance.push(Number.MAX_VALUE)
          }

        })
      }
    },

    async getRecommendInfo() {
      const res = await this.$require({
        url: '/product/recommend',
        method: 'get'
      })
      if (res.status == 0) {
        this.recommendList = res.data
      }
    },

  },

}
</script>
<style scoped lang="scss">
.detail {
  height: 100vh;
  position: relative;
  width: 100%;
  height: 100%;
  background: #eee;
}

.navBar {
  box-sizing: border-box;
  overflow: hidden;
  position: fixed;
  z-index: 99;
  left: 0;
  top: 0;
  background-color: #fff;
  border-bottom: 1px solid #dcdcdc;
  span {
    font-size: 14px;
  }
  .leftInfo {
    font-size: 20px;
    font-weight: 500;
    display: block;
  }
  .centerInfo {
    display: flex;
    justify-content: space-around;
    span {
      margin: 0 10px;
    }
  }
  .right-icon {
    font-size: 20px;
    font-weight: 500;
    display: block;
  }
}
.content {
  position: absolute;
  left: 0;
  right: 0;
  top: 50px;
  bottom: 40px;
}
.active {
  color: #f63515;
}

.slide {
  width: 100%;
  height: 350px;
}
.delateInfo {
  width: 100%;
  height: 150px;
  padding: 10px 15px;
  box-sizing: border-box;
  background-color: #fff;
  p {
    font-size: 16px;
    color: #999999;
  }
  .title {
    color: #333;
    font-size: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  .desc {
    padding-top: 5px;
    margin-bottom: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .price {
    font-size: 22px;
    color: #f63515;
  }
}
.desc {
  p {
    height: 10px;
    width: 100%;
    background-color: #eee;
  }
}
.delate-desc {
  display: flex;
  align-items: center;
  justify-content: space-between;
  text-align: center;
  height: 30px;
  margin: 10px 0;
  background-color: #fff;

  li {
    flex: 1;
    font-size: 14px;
    padding: 5px 0;
    box-sizing: border-box;
    &:not(:first-child) {
      border-left: 1px solid #999;
    }
  }
}
.desc-info {
  width: 100%;
  overflow: hidden;

  p {
    width: 100%;
    font-size: 40px;
    text-align: center;
  }
  /deep/ img {
    width: 100%;
    height: 100%;
  }
}

.footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;

  position: fixed;
  width: 100%;
  z-index: 1000;
  bottom: 0;
  background-color: #fff;
  .item {
    min-width: 50px;
    color: #646566;
    text-align: center;
    span {
      display: block;
      margin-top: 3px;
    }
  }
  .handle {
    flex: 1;
    a {
      display: inline-block;
    }
    .addCart,
    .buy {
      width: 50%;
      height: 40px;
      line-height: 40px;
      color: #fff;
      font-size: 15px;
    }
    .addCart {
      // 左上 右下 右上 左下
      border-radius: 20px 0 0 20px;
      background: linear-gradient(90deg, #ffd01e, #ff8917);
    }
    .buy {
      border-radius: 0 20px 20px 0;
      background: linear-gradient(90deg, #ff6034, #ee0a24);
    }
  }
}
.recommendList {
  margin-top: 5px;
}
</style>
